# Create your views here.
#coding:utf-8
import os
from django.conf import settings
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib.auth import authenticate,login as auth_login,logout as auth_logout
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.contrib import messages
from django.utils.translation import ugettext_lazy as _
from wall.models import *
from bookwall.models import *
from models import *
from forms import *
from PIL import Image


DEFAULT_FORMAT = ".jpg"
def index(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('setting_page'))
    form = LoginForm()
    if request.method == "POST":
        form = LoginForm(request.POST.copy())
        if form.is_valid():
            email = form.cleaned_data['email']
            user = None
            try:
                user = User.objects.get(email = email)
            except User.DoesNotExist:
                pass
            if user :
                if _login(request,user.username,form.cleaned_data['password']):
                    rem = request.POST.getlist('remember')
                    if len(rem) == 0:
                        request.session.set_expiry(0)
                    else :
                        request.session.set_expiry(60 * 60 * 24 * 7)
                    return HttpResponseRedirect(reverse('setting_page'))
            else :
                messages.error(request,"邮箱不存在")
                return HttpResponseRedirect(reverse('login_page'))
    return render_to_response("chuxin.html",{"form" : form},RequestContext(request))

@login_required(login_url="/login/?next=/")
def profile(request):
    userprofile = UserProfile.objects.get(user = request.user)
    usermessage = UserMessage.objects.filter(user = request.user,isviewed = False)
    request.session['notifications'] = usermessage
    return render_to_response("profile.html",{"user":userprofile,"other":userprofile,"num":len(usermessage),"unviewed" : usermessage},RequestContext(request))


@login_required(login_url="/login/?next=/")
def usermessage(request):
    usermessage = request.session['notifications']
    titles = []
    dic = {}
    for notif in usermessage:
        #titles.append(WallList.objects.get(pk = notif.detail_id).title) 
        key = WallList.objects.get(pk = notif.detail_id).title
        dic[key] = notif
    return render_to_response("notifications.html",{"usermessage":dic},RequestContext(request))


@login_required(login_url = "/login/?next=/")
def other_profile(request,uid):
    user = None
    print uid
    try :
        user = User.objects.get(pk = int(uid))
    except:
        pass

    if user:
        userprofile = UserProfile.objects.get(user = user)
        walllist = WallList.objects.filter(user = user)
        return render_to_response("otherprofile.html",{"user":userprofile,"walllist":walllist},RequestContext(request))
    return HttpResponseRedirect("404.html")

def login_page(request):
    form = LoginForm()
    if request.method == "POST":
        form = LoginForm(request.POST.copy())
        if form.is_valid():
            email = form.cleaned_data['email']
            user = None
            try:
                user = User.objects.get(email = email)
            except User.DoesNotExist:
                pass
            if user:
                if _login(request, user.username, form.cleaned_data['password']):
                    remember = request.POST.getlist('remember')
                    if len(remember) == 0:
                        request.session.set_expiry(0)
                    else:
                        request.session.set_expiry(60 * 60 * 24 * 7)
                    return HttpResponseRedirect(reverse('profile'))
            else:
                messages.error(request, "邮箱不存在")
                return HttpResponseRedirect(reverse('login_page'))
    return render_to_response("login.html",{"form":form},RequestContext(request))
                        


    return render_to_response("login.html",{},RequestContext(request))

def signin_page(request):
    form = RegisterForm() 
    if request.method == "POST":
        form = RegisterForm(request.POST.copy())
        if form.is_valid():
            username = form.cleaned_data["username"]
            email = form.cleaned_data["email"]
            password = form.cleaned_data["password"]
            user = User.objects.create_user(username,email)
            user.username = str(user.id) + "_" + username
            user.first_name = username
            user.set_password(password)
            user.save()
            _login(request,user.username,password)
            userprofile = UserProfile.objects.create(user = user)
            userprofile.save()
            return HttpResponseRedirect(reverse('setting_page'))

    return render_to_response("signin.html",{"form": form},RequestContext(request))

@login_required(login_url = '/?next=/')
def setting_page(request):
    user = request.user
    userprofile = UserProfile.objects.get(user = user)
    form = DetailForm(initial = {'username' : user.first_name})
    if request.method == "POST":
        form = DetailForm(request.POST.copy())
        if form.is_valid():
            username = form.cleaned_data['username']
            personalsite = form.cleaned_data['blog']
            position = form.cleaned_data['position']
            resume = form.cleaned_data['selfnote']
            user.first_name = username
            user.save()
            userprofile.address = position
            userprofile.resume = resume
            userprofile.save_without_img()
            return render_to_response("settings.html",{"user" : userprofile,"form" : form},RequestContext(request))
    return render_to_response("settings.html",{"user":userprofile,"form" : form},RequestContext(request))

def icon_page(request):
    form = UploadForm()
    userprofile = UserProfile.objects.get(user = request.user)
    if request.method == "POST":
        form = UploadForm(request.POST,request.FILES)
        if not "head160" in request.FILES:
            return render_to_response("icon.html",{"user":userprofile,"form":form},RequestContext(request))
        #extension = os.path.splitext(request.FILES['head160'].name)[1]
        size =  request.FILES['head160'].size 
        if size > 5 * 1024 * 1024:
            return render_to_response("icon.html",{"user":userprofile,"form":form},RequestContext(request))
        rfile = request.FILES['head160']
        image = Image.open(rfile)
        image.name = str(request.user.id) + "_160" + DEFAULT_FORMAT
        url = "head_img/" + image.name
        name = settings.MEDIA_ROOT + "/" + url
        userprofile.head = "head_img/" + str(request.user.id) + "_48" + DEFAULT_FORMAT
        userprofile.head160 = "head_img/" + str(request.user.id) + "_160" + DEFAULT_FORMAT
        print "hh"
        if form.is_valid():
            print "aa"
            image.save(name,"jpeg")
            userprofile.save()
    return render_to_response("icon.html",{"user":userprofile,"form":form},RequestContext(request))

@login_required(login_url="/login/?next=/")
def reset_pwd(request):
    form = ModifyPwdForm()
    user = request.user
    userprofile = UserProfile.objects.get(user = user)
    if request.method == "POST":
        form = ModifyPwdForm(request.POST.copy())
        if form.is_valid():
            old_password = form.cleaned_data['oldpassword']
            if not request.user.check_password(old_password):
                messages.error(request,"密码错误")
                form = ModifyPwdForm()
                return render_to_response("password.html",{"user":userprofile,"form":form},RequestContext(request))
            password = form.cleaned_data['password']
            user.set_password(password)
            user.save()
            form = ModifyPwdForm()
            return render_to_response("password.html",{"user": userprofile,"form":form},RequestContext(request))
    return render_to_response("password.html",{"user":userprofile,"form":form},RequestContext(request))


def mail_notif(request):
    return render_to_response("mail.html",{"user":request.user},RequestContext(request))

def sync(request):
    return render_to_response("sync.html",{"user":request.user},RequestContext(request))

def _login(request,username,password):
    user = authenticate(username = username, password = password)
    if user is not None:
        auth_login(request,user)
        return True
    else :
        messages.error(request,"邮箱不存在或密码错误")
        return False

def logout(request):
    auth_logout(request)
    return HttpResponseRedirect(reverse('index'))
